<?php
// +----------------------------------------------------------------------
// | [RhaPHP System] Copyright (c) 2017 http://www.rhaphp.com/
// +----------------------------------------------------------------------
// | [RhaPHP] 并不是自由软件,你可免费使用,未经许可不能去掉RhaPHP相关版权
// +----------------------------------------------------------------------
// | Author: Geeson <qimengkeji@vip.qq.com>
// +----------------------------------------------------------------------


namespace app\mp\controller;

use app\common\model\MpFriends;
use think\facade\Cache;
use think\Db;
use think\facade\Request;

class Friends extends Base
{
    public $friendMode;

    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    public function index()
    {
        $where = [];
        $nickname = '';
        $times = '';
        $need = '';
        $sex = '';
        if (Request::isGet()) {
            $_data = input('get.');
            $nickname = isset($_data['nickname']) ? $_data['nickname'] : '';
            $where = [];
            if (isset($_data['nickname'])) {
                $where[] = ['nickname', 'like', "%{$_data['nickname']}%"];
            }
            if (isset($_data['times'])) {
                $times = explode('到', $_data['times']);
                if (count($times) == 2) {
                    $where[] = ['subscribe_time', 'between', [strtotime($times[0]), strtotime($times[1]) + 86400]];
                }
                $times = $_data['times'];
            }
            if (isset($_data['need']) && $_data['need'] == 1) {

                $where[] = ['last_time', '>', (time() - (86400 * 2))];
                $need = 1;
            }
            if (isset($_data['sex']) && $_data['sex'] != 0) {
                $sex = $_data['sex'] ? $_data['sex'] : '0';
                $where[] = ['sex', '=', $_data['sex']];
            }
        }
        $post['nickname'] = $nickname;
        $post['times'] = $times;
        $post['need'] = $need;
        $post['sex'] = $sex;
        $FriendList = MpFriends::where(['mpid' => $this->mid, 'subscribe' => 1])
            ->where($where)
            ->order('subscribe_time DESC')->paginate(20);
        $wechatObj = getWechatActiveObj();
        $tab_list = $wechatObj->getTabList();

        if(is_array($tab_list) && !empty($tab_list)){
            $new_tab_list = array();
            foreach ($tab_list as $item) {
                $new_tab_list[$item['id']] = $item;
            }
            foreach ($FriendList as $k=>$item) {
                $FriendList[$k]['tab_list'] = array();
                if($item['tagid_list']){
                    $tabid_arr = json_decode($item['tagid_list'],true);
                    $tabid_arr = is_array($tabid_arr) ? $tabid_arr : array();
                    $tabs = array();
                    foreach ($tabid_arr as $tab_id) {
                        if(isset($new_tab_list[$tab_id])){
                            $tabs[] = $new_tab_list[$tab_id];
                        }
                        $FriendList[$k]['tab_list'] = $tabs;
                    }
                }
            }
            $tab_json = json_encode($tab_list);

        }else{
            $tab_json = '';
        }


        $this->assign('tab_json', $tab_json);
        $this->assign('friendList', $FriendList);
        $this->assign('post', $post);
        return view();
    }



    public function tabList()
    {
        $wechatObj = getWechatActiveObj();
        $tab_list = $wechatObj->getTabList();
        $this->assign('tab_list', $tab_list);
        return view();
    }

    public function editTab()
    {
        $post = input('post.');
        $id = isset($post['id']) && $post['id'] > 0 ? intval($post['id']): 0;

        if(!isset($_POST['name']) || strlen(trim($_POST['name'])) == 0){
            $return = array(
                'errcode'=>-1,
                'errmsg'=>'请输入标签名',
            );
            echo json_encode($return);
            exit();
        }

        $wechatObj = getWechatActiveObj();
        $result = $wechatObj->editTab($id,trim($_POST['name']));

        if(is_array($result)){
            echo json_encode($result);
        }else{

            if ($wechatObj->errCode == '-1') {
                $message = '系统繁忙';
            }else  if ($wechatObj->errCode == '45157') {
                $message = '标签名非法，请注意不能和其他标签重名';
            }else  if ($wechatObj->errCode == '45158') {
                $message = '标签名长度过长';
            }else  if ($wechatObj->errCode == '45056') {
                $message = '创建的标签数过多，请注意不能超过100个';
            }else{
                 $message = isset($wechatObj->errMsg) && !empty($wechatObj->errMsg) && $wechatObj->errMsg != 'nono access' ? $wechatObj->errMsg: '操作失败';
            }
            $return = array(
                'errcode'=>-1,
                'errmsg'=>$message
            );
            echo json_encode($return);

        }

    }

    public function editMark()
    {
        $post = input('post.');
        $openid = isset($post['openid']) && $post['openid'] ? trim($post['openid']): '';

        if(!$openid){
            $return = array(
                'errcode'=>-1,
                'errmsg'=>'粉丝不存在',
            );
            echo json_encode($return);
            exit();
        }

        $wechatObj = getWechatActiveObj();
        $result = $wechatObj->editMark($openid,trim($_POST['mark']));

        if(is_array($result)){
            MpFriends::where(['mpid' => $this->mid, 'openid' => $openid])->update(array('remark'=>trim($_POST['mark'])));
            echo json_encode($result);
        }else{

            if ($wechatObj->errCode == '-1') {
                $message = '系统繁忙';
            }else  if ($wechatObj->errCode == '45157') {
                $message = '标签名非法，请注意不能和其他标签重名';
            }else  if ($wechatObj->errCode == '45158') {
                $message = '标签名长度过长';
            }else  if ($wechatObj->errCode == '45056') {
                $message = '创建的标签数过多，请注意不能超过100个';
            }else{
                  $message = isset($wechatObj->errMsg) && !empty($wechatObj->errMsg) && $wechatObj->errMsg != 'nono access' ? $wechatObj->errMsg: '操作失败';

            }
            $return = array(
                'errcode'=>-1,
                'errmsg'=>$message
            );
            echo json_encode($return);

        }

    }
    public function editFriendTab(){
        $post = input('post.');
        $tagid_str = isset($post['tid']) ? $post['tid']: '';
        $openid = isset($post['opid']) ? $post['opid']: '';
        $friend = MpFriends::where(['mpid' => $this->mid,'openid' => $openid])->find();
        if(!$openid || !$friend){
            $return = array(
                'errcode'=>-1,
                'errmsg'=>'粉丝不存在',
            );
            echo json_encode($return);
            exit();
        }
        $tagid_list = explode(',',$tagid_str);
        $tagid_list = is_array($tagid_list) ? $tagid_list : array();
        $my_taglist = json_decode($friend['tagid_list'], true);
        $my_taglist = is_array($my_taglist) ? $my_taglist : array();
        $add_taglist = array_diff($tagid_list,$my_taglist);

        $cancel_taglist = array_diff($my_taglist,$tagid_list);

        $wechatObj = getWechatActiveObj();
        $result = 1;
        if(array_values($add_taglist)){

            $result = $wechatObj->addFriendTab($add_taglist,$openid);
        }

        if($result){

            if(array_values($cancel_taglist)){

                $result = $wechatObj->cancelFriendTab($cancel_taglist,$openid);

                if($result){
                    $return = array(
                        'errcode'=>0,
                    );
                    MpFriends::where(['mpid' => $this->mid, 'openid' => $openid])->update(array('tagid_list'=>@json_encode($tagid_list,true)));
                    echo json_encode($return);
                }else{
                    if ($wechatObj->errCode == '-1') {
                        $message = '系统繁忙';
                    }else  if ($wechatObj->errCode == '45159') {
                        $message = '非法的标签';
                    }else  if ($wechatObj->errCode == '45059') {
                        $message = '有粉丝身上的标签数已经超过限制，即超过20个';
                    }else  if ($wechatObj->errCode == '40003') {
                        $message = '传入非法的openid';
                    }else  if ($wechatObj->errCode == '49003') {
                        $message = '传入的openid不属于此AppID';
                    }else{
                         $message = isset($wechatObj->errMsg) && !empty($wechatObj->errMsg) && $wechatObj->errMsg != 'nono access' ? $wechatObj->errMsg: '操作失败';

                    }

                    $return = array(
                        'errcode'=>-1,
                        'errmsg'=>$message
                    );
                    echo json_encode($return);

                }
            }else{
                $return = array(
                    'errcode'=>0,
                );
                MpFriends::where(['mpid' => $this->mid, 'openid' => $openid])->update(array('tagid_list'=>@json_encode($tagid_list,true)));
                echo json_encode($return);
            }


        }else{
            if ($wechatObj->errCode == '-1') {
                $message = '系统繁忙';
            }else  if ($wechatObj->errCode == '45159') {
                $message = '非法的标签';
            }else  if ($wechatObj->errCode == '45059') {
                $message = '有粉丝身上的标签数已经超过限制，即超过20个';
            }else  if ($wechatObj->errCode == '40003') {
                $message = '传入非法的openid';
            }else  if ($wechatObj->errCode == '49003') {
                $message = '传入的openid不属于此AppID';
            }else{
                 $message = isset($wechatObj->errMsg) && !empty($wechatObj->errMsg) && $wechatObj->errMsg != 'nono access' ? $wechatObj->errMsg: '操作失败';
            }
            $return = array(
                'errcode'=>-1,
                'errmsg'=>$message
            );
            echo json_encode($return);

        }



    }

    public function deleteTab()
    {
        $post = input('post.');
        $id = isset($post['id']) && $post['id'] > 0 ? intval($post['id']): 0;
        if($id<=0){
            $return = array(
                'errcode'=>-1,
                'errmsg'=>'标签不存在',
            );
            echo json_encode($return);
            exit();
        }

        $wechatObj = getWechatActiveObj();
        $result = $wechatObj->deleteTab($id);

        if(is_array($result)){
            echo json_encode($result);

        }else{

            if ($wechatObj->errCode == '-1') {
                $message = '系统繁忙';
            }else  if ($wechatObj->errCode == '45058') {
                $message = '不能修改0/1/2这三个系统默认保留的标签';
            }else  if ($wechatObj->errCode == '45057') {
                $message = '该标签下粉丝数超过10w，不允许直接删除';
            }else{
                 $message = isset($wechatObj->errMsg) && !empty($wechatObj->errMsg) && $wechatObj->errMsg != 'nono access' ? $wechatObj->errMsg: '操作失败';
            }
            $return = array(
                'errcode'=>-1,
                'errmsg'=>$message
            );
            echo json_encode($return);

        }

    }




    public function SynFriends()
    {
        ini_set('max_execution_time', '0');
        $this->assign('url', '');
        $this->assign('jdtCss', '');
        $page = input('page');
        $page = $page ? $page : 0;
        $IN = input();
        $next_openid = isset($IN['next_openid']) ? $IN['next_openid'] : null;
        $wechatObj = getWechatActiveObj();
        $table = config('database.prefix') . 'syn_openid';
        $sql = "DELETE FROM {$table} WHERE openid IN (SELECT * FROM(SELECT openid FROM {$table} WHERE mpid = {$this->mid}  GROUP BY openid HAVING COUNT(openid) > 1) AS b) AND id NOT IN (SELECT * FROM (SELECT MIN(id) FROM {$table} WHERE mpid = {$this->mid}  GROUP BY openid HAVING COUNT(openid) > 1) AS c)";
        Db::execute($sql);
        $opneidTotal = Db::name('syn_openid')->where('mpid', '=', $this->mid)->count('distinct(openid)');
        $friendTotal = session($this->mid . 'friendTotal');
        if ($opneidTotal >= $friendTotal  && $friendTotal >0) {
            $synOpenids = Db::name('syn_openid')->where('mpid', '=', $this->mid)
                ->distinct(true)
                ->field('openid')
                ->paginate(100);
            if (!empty($synOpenids->items())) {
                $openids['user_list'] = [];
                foreach ($synOpenids as $key => $val) {
                    $openids['user_list'][$key]['openid'] = $val['openid'];
                }
                $friends_array = $wechatObj->getUsersInfo($openids);
                if (isset($friends_array['user_info_list']) && is_array($friends_array['user_info_list'])) {
                    foreach ($friends_array['user_info_list'] as $value) {
                        $value['mpid'] = $this->mid;
                        $value['tagid_list'] = @json_encode($value['tagid_list'], true);
                        if (Db::name('mp_friends')->where(['mpid' => $this->mid, 'openid' => $value['openid']])->field('id')->find()) {
                            Db::name('mp_friends')->where(['mpid' => $this->mid, 'openid' => $value['openid']])->update($value);
                        } else {
                            Db::name('mp_friends')->insert($value);
                        }
                    }
                }
                $url = getHostDomain() . url('mp/Friends/SynFriends', ['page' => $page + 1]);
                $jdtCss = abs(ceil(((100 * $page / $friendTotal) * 100)));
                if ($jdtCss > 100) {
                    $jdtCss = 100;
                }
                $this->assign('text', $jdtCss . '%');
                $this->assign('jdtCss', $jdtCss . '%');
                $this->assign('url', $url);
            } else {
                $this->assign('jdtCss', '100%');
                $this->assign('text', '同步完成');
                Db::name('syn_openid')->where('mpid', '=', $this->mid)->delete();
            }
            return view('friend');
        }
        $friendList = $wechatObj->getUserList($next_openid);
        session($this->mid . 'friendTotal', $friendList['total']);
        if (!empty($friendList) && $friendList['count'] > 0) {
            $openids = array_chunk($friendList['data']['openid'], 5000);
            foreach ($openids as $key => $val) {
                foreach ($val as $key1 => $opneid) {
                    $openid_list[$key][$key1] = [
                        'openid' => $opneid,
                        'mpid' => $this->mid
                    ];
                }
                Db::name('syn_openid')->insertAll($openid_list[$key]);
            }
            $url = getHostDomain() . url('mp/Friends/SynFriends', ['next_openid' => $friendList['next_openid']]);
            $jdtCss = abs(ceil(($opneidTotal / $friendList['total'] * 100)));
            $this->assign('text', '同步openid');
            $this->assign('jdtCss', $jdtCss . '%');
            $this->assign('url', $url);
            return view('friend');
        } else {
            if ($wechatObj->errCode != '40001' && $wechatObj->errCode != '' && $wechatObj->errMsg != '') {
                if ($msg = wxApiResultErrorCode($wechatObj->errCode)) {
                    exit($msg);
                } else {
                    exit('errCode:' . $wechatObj->errCode . 'errMsg:' . $wechatObj->errMsg);
                }
            }
            $this->assign('jdtCss', '100%');
            $this->assign('text', '同步完成');
            return view('friend');
        }
    }

    public function synSelect()
    {
        $IN = input();
        if (!empty($IN) && isset($IN['openids'])) {
            $wechatObj = getWechatActiveObj();
            $friends = [];
            foreach ($IN['openids'] as $key => $val) {
                $results = $wechatObj->getUserInfo($val);
                if ($results) {
                    $friends[$key] = $results;
                    $friends[$key]['mpid'] = $this->mid;
                    $friends[$key]['tagid_list'] = json_encode($friends[$key]['tagid_list']);
                    if (!empty($friends[$key])) {
                        if (Db::name('mp_friends')->where(['mpid' => $this->mid, 'openid' => $val])->find()) {
                            Db::name('mp_friends')->where(['mpid' => $this->mid, 'openid' => $val])->update($friends[$key]);
                            $update = true;
                        } else {
                            $insert = Db::name('mp_friends')->where(['mpid' => $this->mid, 'openid' => $val])->insert($friends[$key]);
                        }
                    }
                } else {
                    if ($msg = wxApiResultErrorCode($wechatObj->errCode)) {
                        ajaxMsg('0', $msg);
                    } else {
                        ajaxMsg('0', '遇到错误：errCode:' . $wechatObj->errCode . 'errMsg:' . $wechatObj->errMsg);
                    }

                }
            }
            if ($update || $insert) {
                ajaxMsg('1', '同步成功');
            }

        } else {
            ajaxMsg('0', '你没有选择要同步的粉丝');
        }

    }


}